<?php
/**
 * Created by PhpStorm.
 * User: songdewei
 * Date: 2017/10/10
 * Time: 下午3:40
 */

namespace App\WeChat\WxApi;

use App\WeChat\WxApi\Message\WxTemplateMessage;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

class WxTemplateMessageApi extends WxApi
{

    /**
     * 添加模板
     * @param $template_id_short
     * @return bool|\Psr\Http\Message\StreamInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Exception
     */
    public static function addTemplate($template_id_short){
        $data = json_encode(['template_id_short'=>$template_id_short]);

        $uri = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=".self::getAccessToken();
        $request = new Request('POST', $uri, [], $data);
        $client = new Client();
        $response = $client->send($request);
        if ($response->getStatusCode() == 200) {
            return $response->getBody();
        } else {
            return false;
        }
    }

    /**
     * 获取所有消息模板
     * @return mixed
     * @throws \Exception
     */
    public static function getAllTemplate(){
        return Http::curlGet("https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=".self::getAccessToken());
    }

    /**
     * 删除模板
     * @param $template_id
     * @return mixed
     * @throws \Exception
     */
    public static function deleteTemplate($template_id){
        $data = json_encode(['template_id'=>$template_id]);
        return Http::curlPost("https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=".self::getAccessToken(), $data);
    }


    /**
     * 发送模板消息
     * @param WxTemplateMessage $message
     * @return string
     * @throws \Exception
     * 返回示例{
     *"errcode":0,
     *"errmsg":"ok",
     *"msgid":200228332
     *}
     */
    public static function sendMessage(WxTemplateMessage $message){
        if (!$message->getTouser()) {
            throw new \Exception('Empty touser value', 1);
        }

        if (!$message->getTemplateId()) {
            throw new \Exception('Empty template_id value', 2);
        }

        if (!$message->getData()) {
            throw new \Exception('Empty data value', 3);
        }

        $uri = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".self::getAccessToken();
        $request = new Request('POST', $uri, [], $message->getMsgContent());
        $client = new Client();
        $response = $client->send($request);

        if ($response->getStatusCode() == 200) {
            return $response->getBody();
        } else {
            return false;
        }
    }
}
